package com.tfblog.blog.controller;


import com.tfblog.blog.entity.Comment;
import com.tfblog.blog.vo.CommentVO;
import com.tfblog.blog.service.CommentService;
import com.tfblog.exception.CodeException;
import com.tfblog.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tfeng
 * @since 2021-04-26
 */
@CrossOrigin
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    /*
    * 保存/回复评论 : 保存到数据库中
    * */
    @Transactional
    @PostMapping("/comments")
    public R saveComment(@RequestBody Comment comment) {
        commentService.save(comment);
        return R.ok().putStatus("评论保存成功",200);
    }

    /*
    * 根据博客id展示评论列表
    * */
    @GetMapping("/list/{blogId}")
    public R listComments(@PathVariable Long blogId) {
        List<CommentVO> comments = commentService.listCommentByBlogId(blogId);
        System.out.println(comments.size());
        for (CommentVO comment : comments) {
            System.out.println(comment);
        }
        return R.ok().put("data",comments);
    }

    /*
    * 根据评论的父id返回对应的父评论信息
    * */
    @GetMapping("/parent/{parentCommentId}")
    public R findParentComment(@PathVariable Long parentCommentId) {
        if (parentCommentId != null) {
            Comment comment = commentService.findParentComment(parentCommentId);
            return R.ok().put("data",comment);
        }else {
            return R.ok().putStatus(CodeException.NOTEXISTED_PARENTCOMMENT.getMsg(),CodeException.NOTEXISTED_PARENTCOMMENT.getStatus());
        }
    }

}

